package com.hooper.iot.face.typeServer;

import com.hooper.iot.face.schedule.DeviceStatusJob;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;

@Component("tcpServer")
@Slf4j
public class TCPServer implements CommandLineRunner {

    @Resource(name = "serverBootstrap")
    private ServerBootstrap serverBootstrap;

    @Resource(name = "tcpSocketAddress")
    private InetSocketAddress tcpIpAndPort;

    @Autowired
    private DeviceStatusJob deviceStatusJob;

    private Channel serverChannel;

    /**
     * @PostConstruct（会导致其他东西不运行）
     */
    public void start() throws Exception {
        serverChannel = serverBootstrap.bind(tcpIpAndPort).sync().channel().closeFuture().sync().channel();
    }

    //@PreDestroy
    public void stop() throws Exception {
        serverChannel.close();
        serverChannel.parent().close();
    }

    public ServerBootstrap getServerBootstrap() {
        return serverBootstrap;
    }

    public void setServerBootstrap(ServerBootstrap serverBootstrap) {
        this.serverBootstrap = serverBootstrap;
    }

    public InetSocketAddress getTcpPort() {
        return tcpIpAndPort;
    }

    public void setTcpPort(InetSocketAddress tcpPort) {
        this.tcpIpAndPort = tcpPort;
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("netty服务器启动中");
        this.start();
//        //启动时就要获取一次，不然下发可能会比这个快 ,此处注释 改为定时任务启动时执行一次
//        deviceStatusJob.getDevice();
        log.info("netty服务器已启动");
    }
}
